<template>
  <div class="supplier-smart-alerts">
    <div 
      v-for="alert in relevantAlerts" 
      :key="alert.id"
      class="alert-item"
      :class="`priority-${alert.priority}`"
      @click="handleAlertClick(alert)"
    >
      <el-tooltip :content="alert.description" placement="top">
        <div class="alert-content">
          <el-icon :size="12" :color="getPriorityColor(alert.priority)">
            <component :is="getAlertIcon(alert.type)" />
          </el-icon>
          <span class="alert-text">{{ alert.title }}</span>
        </div>
      </el-tooltip>
    </div>
    
    <!-- 高风险供应商详情弹窗 -->
    <el-dialog
      v-model="showRiskSuppliersDialog"
      title="高风险供应商详情"
      width="600px"
      :before-close="handleRiskSuppliersDialogClose"
    >
      <div class="risk-suppliers-detail">
        <el-alert
          type="warning"
          show-icon
          :closable="false"
          description="以下供应商评分低于3.0，建议重点关注并改善合作关系"
        />
        
        <el-table
          :data="riskSuppliers"
          style="margin-top: 20px"
          max-height="400"
        >
          <el-table-column prop="name" label="供应商名称" min-width="150" />
          <el-table-column prop="rating" label="评分" width="80">
            <template #default="{ row }">
              <el-rate
                :model-value="Number(row.rating)"
                disabled
                :max="5"
                allow-half
              />
            </template>
          </el-table-column>
          <el-table-column prop="contactPerson" label="联系人" width="100" />
          <el-table-column prop="phone" label="联系电话" width="120" />
          <el-table-column label="操作" width="100" fixed="right">
            <template #default="{ row }">
              <el-button 
                type="primary" 
                size="small" 
                @click="viewSupplierDetail(row)"
              >
                详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleRiskSuppliersDialogClose">关闭</el-button>
          <el-button type="primary" @click="filterRiskSuppliers">筛选显示</el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 待审核供应商详情弹窗 -->
    <el-dialog
      v-model="showPendingSuppliersDialog"
      title="待审核供应商详情"
      width="600px"
      :before-close="handlePendingSuppliersDialogClose"
    >
      <div class="pending-suppliers-detail">
        <el-alert
          type="info"
          show-icon
          :closable="false"
          description="以下供应商需要审核，请及时处理"
        />
        
        <el-table
          :data="pendingSuppliers"
          style="margin-top: 20px"
          max-height="400"
        >
          <el-table-column prop="name" label="供应商名称" min-width="150" />
          <el-table-column prop="contactPerson" label="联系人" width="100" />
          <el-table-column prop="phone" label="联系电话" width="120" />
          <el-table-column prop="createdAt" label="创建时间" width="120">
            <template #default="{ row }">
              {{ formatDate(row.createdAt) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100" fixed="right">
            <template #default="{ row }">
              <el-button 
                type="primary" 
                size="small" 
                @click="viewSupplierDetail(row)"
              >
                详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handlePendingSuppliersDialogClose">关闭</el-button>
          <el-button type="primary" @click="filterPendingSuppliers">筛选显示</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { Warning, InfoFilled, TrendCharts, Coin, Connection } from '@element-plus/icons-vue'
import { computed, ref } from 'vue'
import { ElMessage } from 'element-plus'

interface Alert {
  id: string
  type: 'risk' | 'opportunity' | 'performance' | 'contract'
  title: string
  description: string
  priority: 'high' | 'medium' | 'low'
  action?: string
}

interface Props {
  suppliers: any[]
  stats: any
  maxAlerts?: number
}

const props = withDefaults(defineProps<Props>(), {
  maxAlerts: 3
})

const emit = defineEmits(['alert-action', 'view-detail'])

// 对话框控制
const showRiskSuppliersDialog = ref(false)
const showPendingSuppliersDialog = ref(false)

// 根据供应商数据生成智能提醒
const relevantAlerts = computed(() => {
  const alerts: Alert[] = []
  
  // 高风险提醒
  if (props.stats.riskSuppliers > 0) {
    alerts.push({
      id: 'risk-suppliers',
      type: 'risk',
      title: `检测到 ${props.stats.riskSuppliers} 个高风险供应商`,
      description: '评分低于3.0的合作中供应商需要关注',
      priority: props.stats.riskSuppliers > 2 ? 'high' : 'medium',
      action: 'view_risk_suppliers'
    })
  }
  
  // 合作机会提醒
  const activeSuppliers = props.suppliers.filter(s => s.status === 'active')
  const lowRatedActiveSuppliers = activeSuppliers.filter(s => 
    typeof s.rating === 'number' ? s.rating < 3.0 : parseFloat(s.rating) < 3.0
  )
  
  if (lowRatedActiveSuppliers.length > 0) {
    alerts.push({
      id: 'improve-relationship',
      type: 'opportunity',
      title: '有供应商关系可改善',
      description: `${lowRatedActiveSuppliers.length} 个合作中供应商评分较低，可考虑改善合作关系`,
      priority: 'medium',
      action: 'review_low_rated_suppliers'
    })
  }
  
  // 待审核提醒
  const pendingSuppliers = props.suppliers.filter(s => s.status === 'pending')
  if (pendingSuppliers.length > 0) {
    alerts.push({
      id: 'pending-review',
      type: 'performance',
      title: `有待审核供应商 (${pendingSuppliers.length} 个)`,
      description: '有待审核的供应商需要及时处理',
      priority: pendingSuppliers.length > 5 ? 'high' : 'medium',
      action: 'review_pending_suppliers'
    })
  }
  
  // 合同到期提醒（模拟数据）
  // 在实际应用中，这里会检查供应商合同到期时间
  const expiringContracts = props.suppliers.filter(s => {
    // 模拟：假设合作日期在30天内需要续签
    if (s.cooperationDate) {
      const cooperationDate = new Date(s.cooperationDate)
      const daysToExpiry = Math.ceil((cooperationDate.getTime() - Date.now()) / (1000 * 60 * 60 * 24))
      return daysToExpiry > 0 && daysToExpiry <= 30
    }
    return false
  })
  
  if (expiringContracts.length > 0) {
    alerts.push({
      id: 'contract-expiry',
      type: 'contract',
      title: `${expiringContracts.length} 个供应商合同即将到期`,
      description: '有供应商合同将在30天内到期，需要及时续签',
      priority: 'high',
      action: 'review_contract_expiry'
    })
  }
  
  return alerts.slice(0, props.maxAlerts)
})

// 高风险供应商列表
const riskSuppliers = computed(() => {
  return props.suppliers.filter(s => 
    s.status === 'active' && 
    (typeof s.rating === 'number' ? s.rating < 3.0 : parseFloat(s.rating) < 3.0)
  )
})

// 待审核供应商列表
const pendingSuppliers = computed(() => {
  return props.suppliers.filter(s => s.status === 'pending')
})

const getPriorityColor = (priority: string) => {
  const colors = {
    high: '#f5222d',
    medium: '#fa8c16',
    low: '#1890ff'
  }
  return colors[priority as keyof typeof colors] || '#1890ff'
}

const getAlertIcon = (type: string) => {
  const icons = {
    risk: Warning,
    opportunity: TrendCharts,
    performance: Coin,
    contract: Connection
  }
  return icons[type as keyof typeof icons] || InfoFilled
}

const handleAlertClick = (alert: Alert) => {
  switch (alert.action) {
    case 'view_risk_suppliers':
      showRiskSuppliersDialog.value = true
      break
    case 'review_pending_suppliers':
      showPendingSuppliersDialog.value = true
      break
    default:
      emit('alert-action', alert)
  }
}

const handleRiskSuppliersDialogClose = () => {
  showRiskSuppliersDialog.value = false
}

const handlePendingSuppliersDialogClose = () => {
  showPendingSuppliersDialog.value = false
}

const filterRiskSuppliers = () => {
  showRiskSuppliersDialog.value = false
  emit('alert-action', { action: 'view_risk_suppliers' })
}

const filterPendingSuppliers = () => {
  showPendingSuppliersDialog.value = false
  emit('alert-action', { action: 'review_pending_suppliers' })
}

const viewSupplierDetail = (supplier: any) => {
  emit('view-detail', supplier)
}

const formatDate = (dateString: string | undefined) => {
  if (!dateString) return '-'
  try {
    const date = new Date(dateString)
    if (isNaN(date.getTime())) return dateString
    return date.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit'
    })
  } catch (error) {
    return dateString
  }
}
</script>

<style scoped lang="scss">
.supplier-smart-alerts {
  display: flex;
  flex-direction: column;
  gap: 4px;
  
  .alert-item {
    padding: 4px 6px;
    border-radius: 4px;
    cursor: pointer;
    transition: all 0.3s ease;
    
    &:hover {
      transform: translateX(2px);
    }
    
    &.priority-high {
      background: rgba(245, 34, 45, 0.1);
      border: 1px solid rgba(245, 34, 45, 0.2);
    }
    
    &.priority-medium {
      background: rgba(250, 140, 22, 0.1);
      border: 1px solid rgba(250, 140, 22, 0.2);
    }
    
    &.priority-low {
      background: rgba(24, 144, 255, 0.1);
      border: 1px solid rgba(24, 144, 255, 0.2);
    }
    
    .alert-content {
      display: flex;
      align-items: center;
      gap: 4px;
      
      .alert-text {
        font-size: 11px;
        font-weight: 500;
      }
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>